package com.hakim.wfb.customer.service.task;

import com.hakim.wfb.bean.ConsumeRecord;
import com.hakim.wfb.dao.ConsumeRecordDao;
import com.hkfs.fundamental.spring.utils.SpringContextUtils;
import com.hakim.wfb.common.util.DateUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;

/**
 * Created by Administrator on 2017/7/20.
 */
//@Component
public class StaticProfitScheduleRestarter {

    private ConsumeRecordDao consumeRecordDao;

    private final static long ONE_DAY_SECOND = 24 * 60 * 60 * 1000;

    private Timer timer;

    private List<ConsumeRecord> list;

    private void delay() {
        try {
            Thread.sleep(20000);
        } catch (Exception e) {
            ;
        }
    }

    public StaticProfitScheduleRestarter() {
        while (true) {
            try {
                if (SpringContextUtils.getSpringContext() != null)
                    break;

            } catch (Exception e) {
                delay();
                continue;
            }
        }
        consumeRecordDao = (ConsumeRecordDao) SpringContextUtils.getBean("consumeRecordDao");
        list = consumeRecordDao.getAllRunningConsumeRecords();

        for (ConsumeRecord consumeRecord : list) {

            timer = new Timer();
            Date date = new Date();
            if (difOneDay(date, consumeRecord.getCrInvestTime()) == true)
                date = consumeRecord.getCrInvestTime();
            else
                date = DateUtils.getNextDayTime(consumeRecord.getCrInvestTime(), 1);

            timer.schedule(new StaticProfitTask(timer, consumeRecord.getCrRewardRemainCount(), consumeRecord), date, ONE_DAY_SECOND);
        }
    }

    public boolean difOneDay(Date date1, Date date2) {
        Calendar cal1 = Calendar.getInstance();
        Calendar cal2 = Calendar.getInstance();

        long s1 = cal1.getTimeInMillis();
        long s2 = cal2.getTimeInMillis();
        if (s2 - s1 > 86400000 || s2 - s1 < -86400000)
            return true;
        return false;
    }
}
